package com.llh.demo4shiro.service;

import com.llh.demo4shiro.model.Authority;
import com.llh.demo4shiro.model.Role;
import com.llh.demo4shiro.model.relation.RoleAuthority;
import com.llh.demo4shiro.repository.AuthorityRepo;
import com.llh.demo4shiro.repository.RoleRepo;
import com.llh.demo4shiro.repository.relation.RoleAuthorityRepo;
import com.llh.demo4shiro.vo.RoleAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>CreatedAt: 2020/9/16 17:28</p>
 *
 * @author llh
 */
@Service
public class RoleService {
    @Autowired
    private RoleRepo roleRepo;
    @Autowired
    private RoleAuthorityRepo roleAuthorityRepo;
    @Autowired
    private AuthorityRepo authorityRepo;

    public List<Role> all() {
        return roleRepo.findAll();
    }

    public Role add(Role role) {

        return roleRepo.save(role);
    }

    public boolean existedRoleName(String roleName) {
        Role role = new Role();
        role.setRoleName(roleName);
        Example<Role> example = Example.of(role);

        long count = roleRepo.count(example);
        return count > 0;
    }

    public int addAuth(RoleAuth roleAuth) {
        RoleAuthority roleAuthority = new RoleAuthority();
        roleAuthority.setRoleId(roleAuth.getRoleId());
        List<RoleAuthority> all = roleAuthorityRepo
                .findAll(Example.of(roleAuthority));
        roleAuthorityRepo.deleteAll(all);
        List<RoleAuthority> list = new ArrayList<>();
        for (Integer aId : roleAuth.getAuthList()) {
            list.add(new RoleAuthority()
                    .setAuthorityId(aId)
                    .setRoleId(roleAuth.getRoleId())
            );
        }
        roleAuthorityRepo.saveAll(list);
        return list.size();
    }

    public List<Authority> getAuth(Integer roleId) {
        RoleAuthority roleAuthority = new RoleAuthority();
        roleAuthority.setRoleId(roleId);
        Example<RoleAuthority> example = Example.of(roleAuthority);
        List<Integer> list = roleAuthorityRepo.findAll(example)
                .stream()
                .map(RoleAuthority::getAuthorityId)
                .collect(Collectors.toList());
        if (list.isEmpty()) return Collections.emptyList();
        return authorityRepo.findAllById(list);
    }

    public List<Authority> getAuth(List<Integer> roleIds) {
        List<RoleAuthority> list = roleAuthorityRepo.findByRoleIdIn(roleIds);
        return authorityRepo.findAllById(list
                .stream()
                .map(RoleAuthority::getAuthorityId)
                .collect(Collectors.toSet()));
    }
}
